// index.ts
// @ts-ignore
import * as echarts from '../../ec-canvas/echarts'
import { formatTime } from '../../utils/util'

let chart = null
// #1aad19 绿
// #F56C6C 红
// #E6A23C 黄
// #63b2ee 蓝

interface pieData {
  name: string
  value: number
}

interface lineData {
  date: string
  value: number
}

interface searchParams {
  date: string
}

interface taskList {
  name: string
  _id: number
  isFinish: boolean
}

interface taskListDateStatic {
  countTrue: number,
  countFalse: number,
  _id: string
}

Component({
  data: {
    isChartChange: false, // 图表数据是否变化
    showModal: false, // 是否显示modal弹框
    isAddTask: true, // 是否点击添加任务按钮
    isDoneTask: false, // 是否点击打卡按钮
    toptipsType: 'error', // 弹框颜色
    errMsg: '',
    inputVal: '',
    taskList: [],
    unfinishTaskList: [] as taskList[], // 未完成的任务,点击打卡后显示在弹框里
    dayCompletePercentList: [
      { name: '已完成', value: 0 },
      { name: '未完成', value: 1 }
    ],
    monthCompletePercentList: [] as lineData[],
    yearCompletePercentList: [] as lineData[],
    dayEc: {
      onInit: null
    },
    monthEc: {
      onInit: null
    },
    yearEc: {
      initYearChart: null
    }
  },

  ready() {
    this.setData({
      'dayEc.onInit': this.initDayChart.bind(this),
      'monthEc.onInit': this.initMonthChart.bind(this),
      'yearEc.onInit': this.initYearChart.bind(this)
    })
    wx.cloud.callFunction({
      name: 'addTodayTask',
      success: () => {
        if (!wx.getStorageSync('openId')) {
          getApp().updateUserInfo().then(() => {
            this.updateTaskList()
          })
        } else {
          this.updateTaskList()
        }
      }
    })
  },

  methods: {
    updateTaskList() {
      wx.showLoading({
        title: '正在获取任务', //提示的内容,
        mask: true
      })
      this.setData({
        isChartChange: false
      })
      this.searchTaskList({ date: formatTime(new Date()) }).then((res: any) => {
        this.setData({
          taskList: res.data
        })
        // 如果折线图加载过了，就不要在重复请求接口了，保证一天只请求一次即可
        if (this.data.monthCompletePercentList.length) {
          wx.hideLoading()
          this.setChartValue()
          return
        }
        // 查询本月数据
        this.dateSearch(formatTime(new Date()).split('-').splice(0, 2).join('-')).then((dateRes: any) => {
          wx.hideLoading()
          dateRes.list = dateRes.list.map((dateItem: taskListDateStatic) => {
            return {
              date: dateItem._id.split('-').splice(1, 3).join('-'),
              value: dateItem.countTrue / (dateItem.countFalse + dateItem.countTrue)
            }
          })
          // 只显示今天之前的数据
          dateRes.list.pop()
          this.setData({
            monthCompletePercentList: dateRes.list
          })
          this.setChartValue()
        })
        // // 查询今年数据
        // this.dateSearch(formatTime(new Date()).split('-').splice(0, 1).join('-')).then((dateRes: any) => {
        //   wx.hideLoading()
        //   dateRes.list = dateRes.list.map((dateItem: taskListDateStatic) => {
        //     return {
        //       date: dateItem._id.split('-').splice(1, 3).join('-'),
        //       value: dateItem.countTrue / (dateItem.countFalse + dateItem.countTrue)
        //     }
        //   })
        //   this.setData({
        //     yearCompletePercentList: dateRes.list
        //   })
        //   this.setChartValue()
        // })
      })
    },

    setChartValue() {
      let dayCompletePercent = this.data.taskList.length ? this.data.taskList.filter((item: taskList) => item.isFinish).length / this.data.taskList.length : 0
      this.setData({
        dayCompletePercentList: [
          { name: '已完成', value: dayCompletePercent },
          { name: '未完成', value: 1 - dayCompletePercent }
        ],
        isChartChange: true
      })
    },

    initDayChart(canvas: any, width: number, height: number, dpr: number) {
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      canvas.setChart(chart)
      let alreadyPercent = this.data.dayCompletePercentList.filter(
        (item: any) => item.name === '已完成'
      )[0].value
      let color = alreadyPercent >= 0.6 ? alreadyPercent >= 0.9 ? ['#1aad19', '#63b2ee'] : ['#1aad19', '#E6A23C'] : ['#1aad19', '#F56C6C']
      let option = this.getPieOption(
        '今日完成度',
        (alreadyPercent * 100).toFixed(0) + '%',
        '#1aad19',
        color,
        this.data.dayCompletePercentList
      )
      chart.setOption(option)
      return chart
    },

    initMonthChart(canvas: any, width: number, height: number, dpr: number) {
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      canvas.setChart(chart)
      let data = this.data.monthCompletePercentList.map((item: any) => item.value)
      let categoryList = this.data.monthCompletePercentList.map((item: any) => item.date)
      let option = this.getLineOption('本月完成度', categoryList, data)
      chart.setOption(option)
      return chart
    },

    initYearChart(canvas: any, width: number, height: number, dpr: number) {
      chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      canvas.setChart(chart)
      let data = this.data.yearCompletePercentList.map((item: any) => item.value)
      let categoryList = this.data.yearCompletePercentList.map((item: any) => item.date)
      let option = this.getLineOption('今年完成度', categoryList, data)
      chart.setOption(option)
      return chart
    },

    getPieOption(
      text: string,
      extraText: string | number,
      extraTextColor: string,
      color: string[],
      data: pieData[]
    ) {
      return {
        title: {
          text,
          left: 'center'
        },
        color,
        graphic: {
          type: 'text',
          left: 'center',
          top: '45%',
          style: {
            text: extraText,
            textAlign: 'center',
            fill: extraTextColor,
            fontSize: 30,
            fontWeight: 700
          }
        },
        series: [
          {
            label: {
              normal: {
                fontSize: 12
              }
            },
            type: 'pie',
            center: ['50%', '50%'],
            radius: ['40%', '60%'],
            data
          }
        ]
      }
    },

    getLineOption(text: string, categoryList: string[], data: number[]) {
      return {
        title: {
          text,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        color: [
          '#63b2ee',
          '#1aad19',
          '#f8cb7f',
          '#f89588',
          '#7cd6cf',
          '#9192ab',
          '#7898e1',
          '#efa666',
          '#eddd86',
          '#9987ce',
          '#63b2ee'
        ],
        xAxis: {
          type: 'category',
          data: categoryList
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data,
            type: 'line',
            smooth: true
          }
        ]
      }
    },

    // 打开添加任务弹框
    handleClickAddTask() {
      this.setData({
        showModal: true,
        inputVal: '',
        isAddTask: true,
        isDoneTask: false
      })
    },

    // 打开打卡弹框
    handleClickDoneTask() {
      let unfinishTaskList: taskList[] = []
      this.data.taskList.forEach((item: taskList) => {
        if (!item.isFinish) {
          unfinishTaskList.push(item)
        }
      })
      if (!this.data.taskList.length) {
        this.setData({
          toptipsType: 'error',
          errMsg: '请设置打卡任务'
        })
        return
      } else {
        if (!unfinishTaskList.length) {
          this.setData({
            toptipsType: 'success',
            errMsg: '恭喜你，完成了今日所有的任务！'
          })
          return
        }
      }
      this.setData({
        unfinishTaskList,
        showModal: true,
        isAddTask: false,
        isDoneTask: true
      })
    },

    // 点击某一项任务
    handleDoneTask(e: any) {
      let index = e.currentTarget.dataset.index
      let taskIsDone = 'unfinishTaskList[' + index + '].isFinish'
      this.setData({
        [taskIsDone]: !this.data.unfinishTaskList[index].isFinish
      })
    },

    handleClickModalBtn (e: any) {
      let index: number = e.detail.index
      // 判断是添加任务还是打卡
      if (this.data.isAddTask) {
        if (index === 1) {
          if (!this.data.inputVal) {
            this.setData({ toptipsType: 'error', errMsg: '请填写任务名称' })
            return
          } else {
            // 调用添加任务的接口
            wx.showLoading({
              title: '添加打卡中', //提示的内容,
              mask: true
            })
            this.addTask(this.data.inputVal).then(() => {
              wx.hideLoading()
              let list = this.data.taskList
              list.push({ name: this.data.inputVal })
              this.setData({ taskList: list })
              this.updateTaskList()
            }).catch((err: any) => {
              wx.showToast({
                title: err, //提示的内容,
                icon: 'none'
              })
              wx.hideLoading()
              wx.hideToast()
            })
          }
        }
      } else if (this.data.isDoneTask) {
        if (index === 1) {
          let doneTaskListIds = this.data.taskList.filter((item: any) => item.isFinish).map((item: any) => item._id)
          if (!doneTaskListIds.length) {
            this.setData({ toptipsType: 'error', errMsg: '您暂未打卡任何一项' })
            return
          } else {
            // 调用打卡接口
            wx.showLoading({
              title: '打卡中', //提示的内容,
              mask: true
            })
            this.editTask(doneTaskListIds).then(() => {
              wx.showToast({
                title: '打卡成功',
                icon: 'success'
              })
              wx.hideLoading()
              wx.hideToast()
              this.setData({
                isChartChange: false
              })
              this.updateTaskList()
            })
          }
        } else if (index === 0) {
          // 点击取消后要把以勾选的打卡状态更改为非打卡状态
          let list = this.data.unfinishTaskList.map((item: taskList) => {
            item.isFinish = false
            return item
          })
          this.setData({ unfinishTaskList: list })
        }
      }
      this.setData({
        showModal: false
      })
    },

    handleDeleteTask() {
      this.deleteTask().then(() => {
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
      })
    },

    // 云函数查找数据库
    searchTaskList(params: searchParams) {
      return new Promise((resolve, reject) => {
        const db = wx.cloud.database() //获取数据库的引用
        db.collection('allUserTask').where({
          _openid: wx.getStorageSync('openId'),
          date: db.RegExp({
            regexp: '.*' + params.date,
            options: 'i'
          })
        }).field({
          _openid: false
        }).get().then((res: any) => {
          resolve(res)
        })
        .catch((err: any) => {
          reject(err)
        })
      })
    },

    // 按照日期查询
    dateSearch (date: Date) {
      return new Promise((resolve, reject) => {
        var db = wx.cloud.database()
        // @ts-ignore
        db.collection('allUserTask').aggregate()
          .match({
            _openid: wx.getStorageSync('openId'),
            date: { "$regex": date }
          })
          .group({
            _id: '$date',
            countFalse: {
              $sum: {
                $cond: [{ $eq: ['$isFinish', false] }, 1, 0]
              }
            },
            countTrue: {
              $sum: {
                $cond: [{ $eq: ['$isFinish', true] }, 1, 0]
              }
            }
          })
          .sort({ _id: 1 })
          .end()
          .then((res: any) => {
            resolve(res)
            console.log(res)
          })
          .catch((err: any) => {
            reject(err)
          })
      })
    },

    addTask(taskName: string) {
      return new Promise((resolve, reject) => {
        const db = wx.cloud.database() //获取数据库的引用
        db.collection('task').add({
          data: {
            name: taskName
          }
        }).then((res: any) => {
          wx.cloud.callFunction({
            name: 'addTodayTask',
            success: () => {
              resolve(res)
            }
          })
        })
        .catch((err: any) => {
          reject(err)
        })
      })
    },

    editTask(ids: string[]) {
      return new Promise((resolve, reject) => {
        const db = wx.cloud.database() //获取数据库的引用
        const _ = db.command
        db.collection('allUserTask').where({
          _openid: getApp().globalData.openId,
          _id: _.in(ids)
          // @ts-ignore
        }).update({
          data: {
            isFinish: true
          }
        }).then((res: any) => {
          resolve(res)
        })
        .catch((err: any) => {
          reject(err)
        })
      })
    },

    deleteTask(taskName: string) {
      return new Promise((resolve, reject) => {
        const db = wx.cloud.database() //获取数据库的引用
        db.collection('allUserTask').where({
          _openid: getApp().globalData.openId,
          name: taskName
          // @ts-ignore
        }).remove().then((res: any) => {
          resolve(res)
        })
        .catch((err: any) => {
          reject(err)
        })
      })
    }
  }
})
